/*
 *  Copyright (c) 2022 李伟国
 *  online-judge is licensed under Mulan PSL v2.
 *  You can use this software according to the terms and conditions of the Mulan PSL v2.
 *  You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 *  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *  See the Mulan PSL v2 for more details.
 */

package edu.platform.controller;

import edu.platform.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping(value = "file")
public class FileController {

    @Autowired
    private IFileService fileService;

    @RequestMapping(value = "image/{filename}", method = RequestMethod.GET)
    public void getImage(@PathVariable("filename")String filename, HttpServletResponse response){
        response.addHeader("Access-Allow-Control-Origin","*");  // 实现跨域
        response.addHeader("Content-type","application/x-www-form-urlencoded");
        String filePath = fileService.findFilePath(filename);
        String suffix = filename.substring(filename.lastIndexOf(".")).replaceAll("\\.","");
        response.setContentType("image/"+suffix);
        try(
                FileInputStream fis = new FileInputStream(filePath);
                ServletOutputStream os = response.getOutputStream();
                ) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while((b=fis.read(buffer))!=-1){
                os.write(buffer,0,b);
            }
        }
        catch (IOException e){
            e.getStackTrace();
        }
    }

    @RequestMapping(value = "image", method = RequestMethod.POST)
    public String uploadImage(MultipartFile file){
        return fileService.addFile(file);
    }

}
